package com.himiotech.core.project.web.system.monitor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.himiotech.core.framework.helper.anno.Log;
import com.himiotech.core.framework.helper.constant.Constants;
import com.himiotech.core.framework.helper.enums.BusinessType;
import com.himiotech.core.framework.helper.utils.ExcelUtil;
import com.himiotech.core.project.helper.exception.TaskException;
import com.himiotech.core.project.helper.utils.job.CronUtils;
import com.himiotech.core.project.model.entity.job.Job;
import com.himiotech.core.project.model.metadata.JobMetadata;
import com.himiotech.core.project.service.IJobService;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Controller
@RequestMapping("/monitor/job")
public class JobController extends HimioBaseController {

    @Autowired
    private IJobService jobService;

    @RequiresPermissions("monitor:job:view")
    @GetMapping
    public String job() {
        return "monitor/job";
    }

    /**
     * 查询定时任务调度列表
     *
     * @param page 分页信息
     * @param job  查询条件
     * @return 表格分页数据
     */
    @RequiresPermissions("monitor:job:list")
    @PostMapping("/list")
    @ResponseBody
    public HimioResult list(Page<Job> page, Job job) {
        handleOrderBy(request, page);
        page = jobService.selectJobListPage(page, job);
        return writeJsonLayuiTable(page);
    }

    /**
     * 导出定时任务调度列表数据
     *
     * @param job 查询条件
     * @return 导出数据
     */
    @Log(title = "定时任务调度 - 导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("monitor:job:export")
    @PostMapping("/export")
    @ResponseBody
    public HimioResult export(Job job) {
        QueryWrapper<Job> query = Wrappers.query();
        if (job != null) {
            query.eq(ObjectUtil.isNotEmpty(job.getJobGroup()), JobMetadata.JOB_GROUP.getColName(), job.getJobGroup());
            query.like(ObjectUtil.isNotEmpty(job.getInvokeTarget()), JobMetadata.INVOKE_TARGET.getColName(), job.getInvokeTarget());
            query.like(ObjectUtil.isNotEmpty(job.getJobName()), JobMetadata.JOB_NAME.getColName(), job.getJobName());
            query.eq(ObjectUtil.isNotEmpty(job.getStatus()), JobMetadata.STATUS.getColName(), job.getStatus());
        }
        List<Job> list = jobService.list(query);
        ExcelUtil<Job> util = new ExcelUtil<>(Job.class);
        return util.exportExcel(list, "定时任务调度");
    }


    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @RequiresPermissions("monitor:job:remove")
    @PostMapping("/remove")
    @ResponseBody
    public HimioResult remove(String ids) throws SchedulerException {
        jobService.deleteJobByIds(ids);
        return writeJsonOk();
    }

    /**
     * 任务调度状态修改
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @RequiresPermissions("monitor:job:changeStatus")
    @PostMapping("/changeStatus")
    @ResponseBody
    public HimioResult changeStatus(Job job) throws SchedulerException {
        Job newJob = jobService.getById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return writeJson(jobService.changeStatus(newJob));
    }

    /**
     * 任务调度立即执行一次
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @RequiresPermissions("monitor:job:changeStatus")
    @PostMapping("/run")
    @ResponseBody
    public HimioResult run(Job job) throws SchedulerException {
        jobService.run(job);
        return writeJsonOk();
    }


    /**
     * 新增保存调度
     */
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @RequiresPermissions("monitor:job:add")
    @PostMapping("/add")
    @ResponseBody
    public HimioResult addSave(@Validated Job job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return writeJsonErr("cron表达式不正确");
        } else if (StrUtil.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return writeJsonErr("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi://'调用");
        }
        return writeJson(jobService.insertJob(job));
    }


    /**
     * 修改保存调度
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @RequiresPermissions("monitor:job:edit")
    @PostMapping("/edit")
    @ResponseBody
    public HimioResult editSave(@Validated Job job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return writeJsonErr("cron表达式不正确");
        } else if (StrUtil.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return writeJsonErr("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi://'调用");
        }
        return writeJson(jobService.updateJob(job));
    }

    /**
     * 校验cron表达式是否有效
     */
    @PostMapping("/checkCronExpressionIsValid")
    @ResponseBody
    public boolean checkCronExpressionIsValid(Job job) {
        return jobService.checkCronExpressionIsValid(job.getCronExpression());
    }
}
